package com.atguigu.gmall.common.rabbit.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.rabbit.model.GmallCorrelationData;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 小兰
 * @Date: 2023/5/8 19:38
 */
@Component
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用于生产者发送消息方法
     */
    public void sendMsg(String exchange, String routingKey, Object msg){
        //调用模板对象发送消息
        //1.构建相关数据,,并存入到redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据的唯一标识
        String redisKey = "mq:"+ UUID.randomUUID().toString().replaceAll("-","");
        correlationData.setId(redisKey);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        //存入redis
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(correlationData),1, TimeUnit.HOURS);
        //2.发送消息时,选择既有业务消息还包括相关消息
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,correlationData);

    }
    /**
     * 用于生产者发送延迟消息方法
     */
    public void sendDelyMsg(String exchange, String routingKey, Object msg,Integer ttlTime){
        //调用模板对象发送消息
        //1.构建相关数据,,并存入到redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据的唯一标识
        String redisKey = "mq:"+ UUID.randomUUID().toString().replaceAll("-","");
        correlationData.setId(redisKey);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        //存入redis
        correlationData.setDelay(true);
        correlationData.setDelayTime(ttlTime);
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(correlationData),ttlTime+600, TimeUnit.SECONDS);
        //2.发送消息时,选择既有业务消息还包括相关消息  为消息设置TTL时间
        //通过参数四消息后置处理器,改写消息属性 为消息设置TTL时间
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,
                (message) ->{
            //为消息改写延迟时间
            message.getMessageProperties().setDelay(ttlTime*1000);
            return message;
                }
                ,correlationData);

    }

}
